<template>
    <div>
        <h1>商品管理</h1>
        <div>
            <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
            >
                <el-form-item label="关键字">
                    <el-input
                        v-model="searchForm.keyWord"
                        placeholder="请输入关键字"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onQuery">查询</el-button>
                    <el-button type="primary" @click="onAddProd"
                        >添加商品</el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="prodId" label="商品ID" width="100" />
                <el-table-column prop="prodName" label="商品名称" width="180" />
                <el-table-column prop="prodPrice" label="价格" width="100" />
                <el-table-column prop="statusName" label="状态" width="120" />
                <el-table-column prop="nickName" label="商户" width="120" />
                <el-table-column prop="typeName" label="类型" width="120" />
                <el-table-column
                    prop="createTime"
                    label="录入时间"
                    width="180"
                />
                <el-table-column prop="reason" label="驳回原因" width="180" />
                <el-table-column label="商品图片" width="180">
                    <template #default="scope">
                        <el-image
                            style="width: 50px; height: 50px"
                            v-if="
                                scope.row.prodImgList != null &&
                                scope.row.prodImgList.length > 0
                            "
                            v-for="item in scope.row.prodImgList"
                            :src="item.imageUrl"
                            :key="item.imageId"
                            fit="cover"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                        <el-button
                            size="small"
                            type="success"
                            v-if="scope.row.prodStatus == 0"
                            @click="handleUpline(scope.row)"
                        >
                            上线
                        </el-button>
                        <el-button
                            size="small"
                            type="success"
                            v-if="scope.row.prodStatus == 1"
                            @click="handleCheck(scope.row)"
                        >
                            审核
                        </el-button>
                        <el-button
                            size="small"
                            type="success"
                            v-if="scope.row.prodStatus == 2"
                            @click="handleDownline(scope.row)"
                        >
                            下线
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="margin-top: 20px">
            <el-pagination
                v-model:current-page="searchForm.pageNum"
                v-model:page-size="searchForm.pageSize"
                :page-sizes="[2, 4, 6, 8]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
                <el-form :model="form">
                    <el-form-item
                        label="商品名称"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品价格"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodPrice" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品类型"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.prodType"
                            placeholder="请选择商品类型"
                        >
                            <el-option
                                v-for="item in typeList"
                                :label="item.dictLabel"
                                :value="item.dictValue"
                                :key="item.dictId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品图片"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            v-model:file-list="fileList"
                            action="http://localhost:10010/user/index/uploadFile"
                            list-type="picture-card"
                            :headers="headers"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>

                        <el-dialog v-model="dialogVisible">
                            <img
                                w-full
                                :src="dialogImageUrl"
                                alt="Preview Image"
                            />
                        </el-dialog>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="onSubmitAddProd">
                            提交
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <div>
            <el-dialog v-model="editFormVisible" title="修改商品" width="500">
                <el-form :model="form">
                    <el-form-item
                        label="商品名称"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品价格"
                        :label-width="formLabelWidth"
                    >
                        <el-input v-model="form.prodPrice" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                        label="商品类型"
                        :label-width="formLabelWidth"
                    >
                        <el-select
                            v-model="form.prodType"
                            placeholder="请选择商品类型"
                        >
                            <el-option
                                v-for="item in typeList"
                                :label="item.dictLabel"
                                :value="item.dictValue"
                                :key="item.dictId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="商品图片"
                        :label-width="formLabelWidth"
                    >
                        <el-upload
                            v-model:file-list="fileList"
                            action="http://localhost:10010/user/index/uploadFile"
                            list-type="picture-card"
                            :headers="headers"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>

                        <el-dialog v-model="dialogVisible">
                            <img
                                w-full
                                :src="dialogImageUrl"
                                alt="Preview Image"
                            />
                        </el-dialog>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="editFormVisible = false"
                            >放弃</el-button
                        >
                        <el-button type="primary" @click="onSubmitUpdateProd">
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <div>
            <el-drawer
                v-model="dialog"
                title="商品审核"
                direction="rtl"
                class="demo-drawer"
            >
                <div class="demo-drawer__content">
                    <el-form :model="checkForm">
                        <el-form-item
                            label="商品名称"
                            :label-width="formLabelWidth"
                        >
                            {{ checkForm.prodName }}
                        </el-form-item>
                        <el-form-item
                            label="商品价格"
                            :label-width="formLabelWidth"
                        >
                            {{ checkForm.prodPrice }}
                        </el-form-item>
                        <el-form-item
                            label="商品类型"
                            :label-width="formLabelWidth"
                        >
                            {{ checkForm.typeName }}
                        </el-form-item>
                        <el-form-item
                            label="商户"
                            :label-width="formLabelWidth"
                        >
                            {{ checkForm.nickName }}
                        </el-form-item>
                        <el-form-item
                            label="商品图片"
                            :label-width="formLabelWidth"
                        >
                            <el-image
                                style="width: 50px; height: 50px"
                                v-if="
                                    checkForm.prodImgList != null &&
                                    checkForm.prodImgList.length > 0
                                "
                                v-for="item in checkForm.prodImgList"
                                :src="item.imageUrl"
                                :key="item.imageId"
                                fit="cover"
                            />
                        </el-form-item>
                        <el-form-item
                            label="审核"
                            :label-width="formLabelWidth"
                        >
                            <el-switch
                                v-model="checkForm.prodStatus"
                                inline-prompt
                                active-text="审核通过"
                                inactive-text="审核不通过"
                                :active-value="2"
                                :inactive-value="3"
                            />
                        </el-form-item>
                        <el-form-item
                            label="审核原因"
                            :label-width="formLabelWidth"
                        >
                            <el-input
                                type="textarea"
                                v-model="checkForm.reason"
                                placeholder="请输入审核原因"
                            />
                        </el-form-item>
                    </el-form>
                    <div class="demo-drawer__footer">
                        <el-button @click="dialog = false">放弃</el-button>
                        <el-button type="primary" @click="onClickCheck">
                            提交审核
                        </el-button>
                    </div>
                </div>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
    getProdList,
    addProd,
    getDictList,
    deleteProd,
    updateProd,
    changeProdStatus,
} from "@/api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
    pageNum: 1,
    pageSize: 2,
    keyWord: null,
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
    prodName: null,
    prodPrice: null,
    prodType: null,
    prodImgList: [],
});
const typeList = ref([]);

const headers = ref({
    token: sessionStorage.getItem("token") || "",
});
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const editFormVisible = ref(false);

const dialog = ref(false);
const checkForm = ref({
    prodId: null,
    prodStatus: null,
    reason: null,
});

// 提交商品审核
const onClickCheck = () => {
    console.log("onClickCheck", checkForm.value.prodStatus);

    changeProdStatus(checkForm.value).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("提交成功");
            dialog.value = false;
            loadList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 申请商品上线
const handleUpline = (row: any) => {
    console.log("handleUpline", row);
    row.prodStatus = 1;
    changeProdStatus(row).then((res) => {
        if (res.data.code == 200) {
            ElMessage.success("提交成功");
            loadList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 商品审核
const handleCheck = (row: any) => {
    console.log("handleCheck", row);
    Object.assign(checkForm.value, row);
    dialog.value = true;
};

// 申请商品下线
const handleDownline = (row: any) => {
    console.log("handleDownline", row);
};

// 显示修改商品对话框
const handleEdit = (row: any) => {
    console.log(row);
    Object.assign(form.value, row);
    //fileList.value = form.value.prodImgList;

    fileList.value = [];
    form.value.prodImgList.forEach((item) => {
        let img = {};
        img.url = item.imageUrl;
        fileList.value.push(img);
    });
    editFormVisible.value = true;
};

// 修改商品
const onSubmitUpdateProd = () => {
    debugger;

    // 把多图数据放入提交的表单
    let prodImgList = [];
    fileList.value.forEach((item) => {
        let img = {};
        if (item.response == undefined) {
            img.imageUrl = item.url;
        } else {
            img.imageUrl = item.response.data;
        }
        prodImgList.push(img);
    });
    form.value.prodImgList = prodImgList;

    // 提交修改
    updateProd(form.value).then((res) => {
        console.log("res", res);
        if (res.data.code == 200) {
            ElMessage.success("修改成功");
            editFormVisible.value = false;
            loadList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 删除商品
const handleDelete = (row: any) => {
    console.log(row);
    ElMessageBox.confirm("删除数据后无法恢复,您确认要删除吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "放弃",
        type: "warning",
    })
        .then(() => {
            // 确认删除
            deleteProd(row.prodId).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success("删除成功");
                    loadList();
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
        })
        .catch(() => {
            // 放弃删除
        });
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
};

// 显示商品添加对话框
const onAddProd = () => {
    dialogFormVisible.value = true;
};

// 提价添加商品
const onSubmitAddProd = () => {
    console.log("filelist", fileList.value);
    fileList.value.forEach((item: any) => {
        let img = {
            imageUrl: item.response.data,
        };
        form.value.prodImgList.push(img);
    });

    addProd(form.value).then((res: any) => {
        if (res.data.code == 200) {
            dialogFormVisible.value = false;
            ElMessage.success("添加商品成功");
            loadList();
        } else {
            ElMessage.error(res.data.msg);
        }
    });
};

// 查询
const onQuery = () => {
    loadList();
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    searchForm.value.pageSize = val;
    loadList();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    searchForm.value.pageNum = val;
    loadList();
};

// 分页获取商品列表
const loadList = () => {
    getProdList(searchForm.value).then((res: any) => {
        if (res.data.code == 200) {
            tableData.value = res.data.data.records;
            total.value = res.data.data.total;
        }
    });
};

// 页面加载钩子函数
onMounted(() => {
    loadList();

    // 获取商品类型列表
    getDictList(1).then((res: any) => {
        if (res.data.code == 200) {
            typeList.value = res.data.data;
        }
    });
});
</script>

<style scoped></style>
